﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Sogeti.QueryWrapper;
using Microsoft.TeamFoundation.Client;
using System.Xml;

using Sogeti.VSExtention;
using Sogeti.QueryWrapper;

namespace Mskold.IterationManager
{
  

    public interface IAction
    {

        string Title { get;  }
        bool Execute(ref Dictionary<string, object> sharedVariables,  ActionNotifyCallbackDelegate notifyCallback);
    }


    public class CreateIterationAction: IAction
    {

        string IAction.Title { get { return "Create Iteration node in Areas & Iterations"; }  }

        bool IAction.Execute(ref Dictionary<string, object> sharedVariables,ActionNotifyCallbackDelegate notifyCallback)
        {
            try
            {
                string iterationName = GetSharedVariable<string>("IterationName", sharedVariables);
                XmlElement node = GetSharedVariable<XmlElement>("InsertMarkNode", sharedVariables);
                TeamExplorerIntergator teamExplorer = GetSharedVariable<TeamExplorerIntergator>("TeamExplorer", sharedVariables);

                XmlElement xParent = (XmlElement)node.ParentNode.ParentNode;

                CommonStructureWrapper csw = new CommonStructureWrapper(teamExplorer.tpCollection);
                XmlNode newIterationNode = csw.CreateNode(iterationName, new Uri(xParent.Attributes["NodeID"].Value.ToString()), GetIndexOfNodeInParent(node));

                notifyCallback(0.99, "Created iteration " + iterationName);

                sharedVariables.Add("NewIterationPath", newIterationNode.Attributes["Path"].Value.ToString());
                return true;

            }
            catch (Exception ex)
            {
                notifyCallback(0.99, "Unexpected error " + ex.Message);
                return false;
            }
            
        }

        private int GetIndexOfNodeInParent(XmlNode n)
        {
            int i = 0;
            while (n.PreviousSibling != null)
            {
                i++;
                n = n.PreviousSibling;
            }


            return i;
        }
        
        public T GetSharedVariable<T>(string name, Dictionary<string,object> sharedVariables )
        {
            object o;
            sharedVariables.TryGetValue(name, out o);
            return (T)o;
        }
        
    }

    public class CreateWorkItemAction : IAction
    {

        string IAction.Title { get { return "Create Sprint  workitem "; } }

        bool IAction.Execute(ref Dictionary<string, object> sharedVariables, ActionNotifyCallbackDelegate notifyCallback)
        {

            try
            {
                string iterationName = GetSharedVariable<string>("IterationName", sharedVariables);
                string iterationPath = GetSharedVariable<string>("NewIterationPath", sharedVariables);
                TeamExplorerIntergator teamExplorer = GetSharedVariable<TeamExplorerIntergator>("TeamExplorer", sharedVariables);
                string sprintWIT = GetSharedVariable<string>("SprintWIT", sharedVariables);
                string startDateField = GetSharedVariable<string>("StartDateField", sharedVariables);
                string finishDateField = GetSharedVariable<string>("FinishDateField", sharedVariables);
                DateTime startDate = GetSharedVariable<DateTime>("StartDate", sharedVariables);
                DateTime finishDate = GetSharedVariable<DateTime>("FinishDate", sharedVariables);

                //TPWiWrapper wi = new TPWiWrapper(teamExplorer.tpCollection.Uri.ToString(), teamExplorer.tpName);
                TPWiWrapper wi = new TPWiWrapper(teamExplorer);
                notifyCallback(0.2, "Initialised ");

                Dictionary<string, object> fields = new Dictionary<string, object>();
                fields.Add(startDateField, startDate);
                fields.Add(finishDateField, finishDate);

                notifyCallback(0.3, "Setup fields, Creating new " + sprintWIT + "Workitem  ");

                wi.CreateWorkItem(sprintWIT, iterationName, iterationPath, fields);
                notifyCallback(0.99, "Saved workitem ");

                return true;
            }
            catch (Exception ex)
            {
                notifyCallback(0.99, "Unexpected error " + ex.Message);
                return false;
            }
        }

        public T GetSharedVariable<T>(string name, Dictionary<string, object> sharedVariables)
        {
            object o;
            sharedVariables.TryGetValue(name, out o);
            return (T)o;
        }
    }

    public class CopyIterationFolderAction : IAction
    {

        string IAction.Title { get { return "Create new query older from template folder "; } }

        bool IAction.Execute(ref Dictionary<string, object> sharedVariables, ActionNotifyCallbackDelegate notifyCallback)
        {
            try
            {
                string iterationName = GetSharedVariable<string>("IterationName", sharedVariables);
                string newIterationPath = GetSharedVariable<string>("NewIterationPath", sharedVariables);
                TeamExplorerIntergator teamExplorer = GetSharedVariable<TeamExplorerIntergator>("TeamExplorer", sharedVariables);
                string masterFolder = GetSharedVariable<string>("TempalteWIQLFolder", sharedVariables);

                //TPQueryWrapper qw = new TPQueryWrapper(teamExplorer.tpCollection.Uri.ToString(), teamExplorer.tpName);
                TPQueryWrapper qw = new TPQueryWrapper(teamExplorer);

                notifyCallback(0.10, "Loading folder " + masterFolder);
                WiqlFolder qryFld = qw.FindWiqlFolder(masterFolder);
                string firstIterationPath = qw.GetUsedIterationsInFolder(qryFld).First();

                ActionNotifyCallback childCallback = new ActionNotifyCallback() { _delegate = notifyCallback, start = 0.3, range = 0.5 };

                if (qryFld != null)
                {
                    qryFld.Path = qryFld.Path.Substring(0, qryFld.Path.LastIndexOf(@"/") + 1) + iterationName;
                    qryFld.Name = iterationName;
                    notifyCallback(0.3, "Replacing " + firstIterationPath + " with " + newIterationPath);

                    if (qryFld != null)
                    {
                        qw.ReplaceIterationinFolder(ref qryFld, firstIterationPath, newIterationPath, childCallback);

                        notifyCallback(0.8, "Saving query folder " + iterationName);

                        qw.SaveQueryFolder(qryFld);
                        notifyCallback(0.99, "Created query folder " + iterationName + " from template");
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                notifyCallback(0.99, "Unexpected error " + ex.Message);
                return false;
            }
        }
          public T GetSharedVariable<T>(string name, Dictionary<string, object> sharedVariables)
        {
            object o;
            sharedVariables.TryGetValue(name, out o);
            return (T)o;
        }
    }
    public class ReplaceIterationInFolderAction : IAction
    {


        public string myTitle;

        public  ReplaceIterationInFolderAction(string title)
        {
            myTitle = title;
        }

        public  ReplaceIterationInFolderAction()
        {
            myTitle = "Create new query folder from template folder ";
        }

        string IAction.Title { get { return myTitle; } }


        bool IAction.Execute(ref Dictionary<string, object> sharedVariables, ActionNotifyCallbackDelegate notifyCallback)
        {
            try
            {
                TeamExplorerIntergator teamExplorer = GetSharedVariable<TeamExplorerIntergator>("TeamExplorer", sharedVariables);
                string currentIterationFolder = GetSharedVariable<string>("CurrentIterationFolder", sharedVariables);
                string fromIterationPath = GetSharedVariable<string>("FromIterationPath", sharedVariables);
                
                string toIterationPath = GetSharedVariable<string>("ToIterationPath", sharedVariables);

                //TPQueryWrapper qw = new TPQueryWrapper(teamExplorer.tpCollection.Uri.ToString(), teamExplorer.tpName);
                TPQueryWrapper qw = new TPQueryWrapper(teamExplorer);

                notifyCallback(0.10, "Loading folder " + currentIterationFolder);

                WiqlFolder currentFolder;
                currentFolder = qw.FindWiqlFolder(currentIterationFolder);

                ActionNotifyCallback childCallback = new ActionNotifyCallback() { _delegate = notifyCallback, start = 0.3, range = 0.5 };

                if (currentFolder != null)
                {
                    notifyCallback(0.3, "Replacing " + fromIterationPath + " with " + toIterationPath);
                

                    qw.ReplaceIterationinFolder(ref currentFolder, fromIterationPath, toIterationPath, childCallback);



                    notifyCallback(0.8, "Saving query folder " + currentIterationFolder);

                    qw.SaveQueryFolder(currentFolder);
                    notifyCallback(0.99, "Replaced iteration in query folder " + currentIterationFolder);
                    
                }
                return true;
            }
            catch (Exception ex)
            {
                notifyCallback(0.99, "Unexpected error " + ex.Message);
                return false;
            }
        }
          public T GetSharedVariable<T>(string name, Dictionary<string, object> sharedVariables)
        {
            object o;
            sharedVariables.TryGetValue(name, out o);
            return (T)o;
        }
    }
          
    
     

    #region "NotUSed???"
 
    public class CopyIterationDefautlWorkItemAction : IAction
    {

        protected string newIterationPath;
        protected string tpCollectionUrl;
        protected string teamProjectName;


        public CopyIterationDefautlWorkItemAction(string aTPCollectionUrl, string aTeamProjectName, string aTargetIterationPth)
        {
            tpCollectionUrl = aTPCollectionUrl;
            teamProjectName = aTeamProjectName;

            newIterationPath = aTargetIterationPth;

        }


        string IAction.Title         {            get { return "Copy Default WI to Iteration " + newIterationPath; }}


        bool IAction.Execute(ref Dictionary<string, object> sharedVariables, ActionNotifyCallbackDelegate notifyCallback)
        {
            newIterationPath = newIterationPath.Replace("\\Iteration\\", "\\").Substring(1);

            TPWiWrapper WIWrapper = new TPWiWrapper(tpCollectionUrl, teamProjectName);

            List<WI> lst = WIWrapper.GetInitialWorkItens();
            foreach (WI itm in lst)
            {
                itm.IterationPath = newIterationPath;
            }
            WIWrapper.CreatWorkItems(lst);
            return true;

        }

    }

    public class CreatePortalSubSiteAction : IAction
    {

        protected string subSiteName;
        protected string tpCollectionUrl;
        protected string teamProjectName;


        public CreatePortalSubSiteAction(string aTPCollectionUrl, string aTeamProjectName, string theSubSiteName)
        {
            tpCollectionUrl = aTPCollectionUrl;
            teamProjectName = aTeamProjectName;

            subSiteName = theSubSiteName;

        }


        string IAction.Title { get { return "Create subsite subsite " + subSiteName; } }
        
        


        bool IAction.Execute(ref Dictionary<string, object> sharedVariables, ActionNotifyCallbackDelegate notifyCallback)
        {
            RegistryWrapper rw = new RegistryWrapper(tpCollectionUrl, teamProjectName);
            string sPortalUrl = rw.GetPortalUrl(teamProjectName);


            //PortalWrapper.SpPortalWrapper sp= new PortalWrapper.SpPortalWrapper(theTpCollectionUrl);
            //sp.CreateSubSite(subSiteName);
            return true;
        }

    }
}
    #endregion

    
